<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\admin\model\ShopOrder;
use app\admin\model\Shop;
use app\admin\model\Product;
use app\admin\model\ProductMessage;
use app\admin\model\OrderLog;
use app\admin\model\User;
use app\admin\model\ChatMessage;
use app\api\controller\Pay;
use think\Db;
use getui\GeTui;
use think\Exception;
/**
 * 订单管理列表
 *
 * @icon fa fa-user
 */
class Order extends Backend
{

    protected $relationSearch = true;
    protected $searchFields = 'id,username,nickname';

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;

    public function _initialize()
    {   
       
        parent::_initialize();
        $this->model = new ShopOrder();
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $filter = json_decode($this->request->get("filter", ''),true);
            $where1 = [];
            if(!empty($filter['name'])){
                $where1 = ['name'=>["LIKE", "%{$filter['name']}%"]];
                unset($filter['name']);
            }
            $filter = json_encode($filter);
            list($where, $sort, $order, $offset, $limit) = $this->buildparams(null,null,$this->model,$filter);
            $list = $this->model->alias('a')
                ->field("a.*,b.name")
                ->join("shop b","b.id = a.shop_id")
                ->where($where)
                ->where($where1)
                ->order($sort, $order)
                ->paginate($limit);
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }
     /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->where('id',$ids)->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $this->token();
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                if((!empty($params['expressage']) && empty($params['odd']))  || (empty($params['expressage']) && !empty($params['odd']))){
                    $this->error('物流单号和快递名称需要同时填写!');
                }
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validate($validate);
                    }
                    //查询当前订单状态和是否填写了物流信息
                    if(($row['status'] == 2 || $row['status'] == 6) && $params['expressage'] && $params['odd']){
                        //都填写了则更新订单状态为已发货
                        $params['status'] = 3;
                        $params['delivery_time'] = time();
                        if($row['notice'] == 1){
                            //发送订阅消息
                            $product = Product::where('id',$row['product_id'])->find();
                            $data = [
                                "thing10"=>["value"=>$product['title']],
                                "phrase8"=>["value"=>'买家付邮'],
                                "character_string3"=>[ "value"=> $params['odd']], 
                                "thing1"=>["value"=>'你的订单已发货，请及时关注物流信息！' ]
                            ];
                            send_subscription($row['user_id'],'UVo1qW8QNqqYqJwaGDtZ10ianotfn5aHyDC3tSqI2iE','/pages/user/myOrder',$data);
                        }
                    }
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $product =  Product::where(['id'=>$row['product_id']])->find();
        //商品名称
        $row['product_name'] = $product['title'];
        //商家id
        $row['shop_id'] = $product['id'];
        //寄件人信息
        $row['jijian'] = $product['name'].$product['phone'].$product['position'].$product['city'].$product['area'].$product['address'];
        //收件人信息
        $row['shoujian'] = $row['address_username'].$row['address_tel'].$row['address_province'].$row['address_city'].$row['address_detail'];
        $row['add_time'] = date('Y-m-d H:i:s',$row['add_time']);

        if($row['status'] == 3 || $row['status'] == 5){
            $row['status_1'] = 1;
        }else{
            $row['status_1'] = 0;
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    public function setQxStatus(){
        if ($this->request->isPost()) {
            $data = $this->request->request();
            if(!$data['id']){
                $this->error('参数错误');
            }
            Db::startTrans();
            try {
                $result = OrderLog::where(['id'=>$data['id']])->update(['status'=>$data['status']]);
                if ($result) {
                    $log = OrderLog::where(['id'=>$data['id']])->find();
                    $order = ShopOrder::where(['id'=>$log['order_id']])->find();
                    if($data['status'] == 1){
                        //同意取消进行退款操作
                        ShopOrder::where(['id'=>$log['order_id']])->update(['status'=>-1]);
                        $arr = ['user_id'=>$log['user_id'],'order_id'=>$order['id'],'ship_type'=>$order['ship_type'],'status'=>$order['status'],'add_time'=>date('Y-m-d H:i:s',time())];
                        if($order['ship_type'] == 1){
                            $arr['text'] = '买家付邮退款';
                            Pay::doOrderRefund($order,$order['pay_fee'],$log['user_id'],$arr);
                        }else{
                            $arr['text'] = '自提取消订单';
                            //退回积分
                            roseandlog($order['user_id'],$order['total_money'],18,'取消订单，退回');
                            $product=Product::where(array('id'=>$order['product_id']))->find();
                            ProductMessage::insert(array('product_id'=>$order['product_id'],'title'=>'买家'.$log['user_id'].'取消订单，取消发货:【'.$product['title'].'】','user_id'=>$order['user_id'],'to_user_id'=>$product['user_id'],'is_read'=>0,'type'=>3,'status'=>1,'add_time'=>time()));
                            Product::where(array('id'=>$order['product_id']))->update(array('is_sale'=>0));
                        }
                        OrderLog::insert($arr);
                        $arr = [
                            'content' => '你的取消申请已成功。',
                            'user_id' => 439,
                            'js_user_id'=> $log['user_id'],
                            'product_id'=>$order['product_id'],
                            'add_time'=>time(),
                        ];
                        $arr['sort'] = $arr['js_user_id'].'0'.$order['product_id'].$arr['user_id'];
                        ChatMessage::insert($arr);
                        
                        //发送订阅推送
                        $data = [
                            'thing1'=>['value'=>'你的领取订单已被赠送者取消'],
                            'character_string2'=>['value'=>$order['order_id']],
                            'time3'=>['value'=>date('Y-m-d H:i:s',$order['add_time'])]
                        ];
                        send_subscription($order['user_id'],'2zbsInw2kF2wH4mLA_Z7do7TrpZ3LQBBERm3LzIpCV8','/pages/user/myOrder',$data);

                        //卖家取消给买家发送消息
                        $geTui = new GeTui();
                        //添加成功执行推送逻辑
                        $cid = User::where(['id'=>['in',$order['user_id']]])->value('cid');
                        if($cid){
                            $geTui->pushToSingleByCid($cid,'订单提醒','您兑换的商品已被卖家取消','/pages/user/myOrder');
                        }
                    }else{ // 拒绝  给用户发送一条消息
                        $arr = [
                            'content' => '你的取消申请被拒绝，请联系余享客服处理。',
                            'user_id' => 439,
                            'js_user_id'=> $log['user_id'],
                            'product_id'=>$order['product_id'],
                            'add_time'=>time(),
                        ];
                        $arr['sort'] = $arr['js_user_id'].'0'.$order['product_id'].$arr['user_id'];
                        ChatMessage::insert($arr);

                        //卖家取消被拒绝给卖家发送消息
                        $geTui = new GeTui();
                        //添加成功执行推送逻辑
                        $cid = User::where(['id'=>['in',$order['shop_id']]])->value('cid');
                        if($cid){
                            $geTui->pushToSingleByCid($cid,'订单提醒','您的取消订单申请已被拒绝','/pages/user/sellOrder');
                        }

                    }
                    Db::commit();
                    $this->success();
                } else {
                    Db::commit();
                    $this->error('操作失败');
                }
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }


            
        }
    }
    public function cancelOrder(){
        if ($this->request->isPost()) {
            $data = $this->request->request();
            if(!$data['id']){
                $this->error('参数错误');
            }
            $order = ShopOrder::where(['id'=>$data['id']])->find();
            if ($order) {
                //取消进行退款操作
                ShopOrder::where(['id'=>$order['id']])->update(['status'=>-1]);
                $arr = ['user_id'=>$order['user_id'],'order_id'=>$order['id'],'ship_type'=>$order['ship_type'],'status'=>$order['status'],'add_time'=>date('Y-m-d H:i:s',time())];
                if($order['ship_type'] == 1){
                    $arr['text'] = '买家付邮退款';
                    Pay::doOrderRefund($order,$order['pay_fee'],$order['user_id'],$arr);
                }else{
                    $arr['text'] = '自提取消订单';
                    //退回积分
                    roseandlog($order['user_id'],$order['total_money'],18,'取消订单，退回');
                    $product=Product::where(array('id'=>$order['product_id']))->find();
                    ProductMessage::insert(array('product_id'=>$order['product_id'],'title'=>'买家'.$order['user_id'].'取消订单，取消发货:【'.$product['title'].'】','user_id'=>$order['user_id'],'to_user_id'=>$product['user_id'],'is_read'=>0,'type'=>3,'status'=>1,'add_time'=>time()));
                    Product::where(array('id'=>$order['product_id']))->update(array('is_sale'=>0));
                }
                OrderLog::insert($arr);
                $this->success();
            } else {
                $this->error('操作失败');
            }
        }
    }
}
